import type { ProColumns } from '@ant-design/pro-components';
import {
  EditableProTable,
} from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import useVariable from '../store/useVariable';


interface Props {
  onChange: (variable: Variable[]) => void;
  value: Variable[];
}

export default (props: Props) => {
  const { onChange, value } = props

  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const { variable, setVariable } = useVariable();

  console.log('=========>1', variable)

  // useEffect(() => {
  //   console.log('editableKeys', editableKeys)
  //  }, [editableKeys])

  const columns: ProColumns<Variable>[] = [
    {
      title: '名称',
      dataIndex: 'label',
      width: 180
    },
    {
      title: '参数',
      dataIndex: 'value',
      width: 100,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '变量名是必填项',
          },
          {
            pattern: /^sys\.[a-zA-Z_$][a-zA-Z0-9_$]*$/,
            message: 'sys.开头加后面自定义变量',
          }
        ],
      },
    },
    {
      title: '必填',
      dataIndex: 'readonly',
      width: 60,
      valueType: 'switch',
      fieldProps: {
        checkedChildren: '必填',
        unCheckedChildren: '非必填',
      },
      valueEnum: {
        true: { text: '必填' },
        false: { text: '非必填' }
      }
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => {
        return record.value !== "sys.query" &&
          record.value !== "sys.result" && record.value?.startsWith("sys.") && [
            <a
              key="editable"
              className='text-blue-500'
              onClick={() => {
                action?.startEditable?.(record.id);
              }}
            >
              编辑
            </a>,
            <a
              key="delete"
              className='text-red-500'
              onClick={() => {
                setVariable(variable.filter((item) => item.id !== record.id));
              }}
            >
              删除
            </a>,
          ]
      },
    },
  ];

  return (
    <EditableProTable<Variable>
      rowKey="id"
      className='rounded-xl'
      recordCreatorProps={
        {
          position: "top",
          record: () => ({ id: (Math.random() * 1000000).toFixed(0) }),
        }
      }
      loading={false}
      columns={columns}
      value={value}
      onChange={onChange}
      editable={{
        type: 'multiple',
        editableKeys,
        onChange: setEditableRowKeys,
      }}
    />
  );
};